#include "Camera.h"
#include "Define.h"
#ifdef _WINDOWS
	#include <Windows.h>
#endif
#include "DebugLog.h"

Camera::Camera(void){}
Camera::~Camera(void){}

Camera* Camera::_instance = nullptr;

Camera* Camera::getSingleton()
{
	if (_instance == nullptr)
	{
		_instance = new Camera();
	}
	return _instance;
}

void Camera::cleanSingleton()
{
	if (_instance != nullptr)
	{
		delete _instance;
		_instance = nullptr;
	}
}

void Camera::move(sf::Vector2f& position)
{
	_position = position;
	_target = position;
}

void Camera::moveToCenter(sf::Vector2f& position)
{
	position.x = position.x - (_size.x * 0.5f);
	position.y = position.y - (_size.y * 0.5f);
	_position = position;
	_target = position;
}

void Camera::goTo(sf::Vector2f& position)
{
	_target = position;
}

void Camera::goToCenter(sf::Vector2f& position)
{
	position.x = position.x - (_size.x * 0.5f);
	position.y = position.y - (_size.y * 0.5f);
	_target = position;
}

void Camera::update()
{
	float x, y, d, vx, vy, v = 0;
	x = _target.x - _position.x;
	y = _target.y - _position.y;
	if ( (x*x + y*y) <= 1.0f )
	{
		_position = _target;
	}
	else
	{
		d = sqrt( (x*x + y*y) );
		v = (d * _speed) / 60.0f;
		if (v < 1.0f)
			v = 1.0f;
		vx = x * (v/d);
		vy = y * (v/d);

		_position.x += vx;
		_position.y += vy;
	}

	if (_position.x < VSW_05) _position.x = VSW_05;
	else if (_position.x > (_mapSize.x - VSW_05)) _position.x = (_mapSize.x - VSW_05);

	if (_position.y < VSH_05) _position.y = VSH_05;
	else if (_position.y > (_mapSize.y - VSH_05)) _position.y = (_mapSize.y - VSH_05);
	//_view->zoom(SCALEF);
	_view->setCenter(_position);
}

sf::IntRect Camera::getTilebounds(int tileSize)
{
	int x = static_cast<int>(_position.x - VSW_05) / tileSize;
	int y = static_cast<int>(_position.y - VSH_05) / tileSize;

	int w = static_cast<int>(_size.x) / tileSize + 2;
	int h = static_cast<int>(_size.y) / tileSize + 2;

	/*if (x % tileSize != 0)
	{
		if (x % tileSize != (w - x))
			w++;
		else
			w--;
	}
	if (y % tileSize != 0)
	{
		if (y % tileSize != (h - y))
			h++;
		else
			h--;
	}*/

	return sf::IntRect(x, y, w, h);
}

void Camera::initialize(std::shared_ptr<sf::View> view, float speed)
{
	_view = view;
	_size = view->getSize();
	_speed = speed;
}